package com.tanhua.app.service;

import com.tanhua.api.*;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.exception.ErrorResult;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.model.dto.AnswersDto;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.soul.*;
import com.tanhua.model.vo.OptionsVo;
import com.tanhua.model.vo.QuestionVo;
import com.tanhua.model.vo.ReportVo;
import com.tanhua.model.vo.TestSoulVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class TestSoulService {


    @DubboReference
    private SoulAskApi soulAskApi;


    @DubboReference
    private SoulQuestionApi soulQuestionApi;


    @DubboReference
    private SoulQuestionOptionApi soulQuestionOptionApi;

    @DubboReference
    private SoulRecordApi soulRecordApi;

    @DubboReference
    private SoulAppraiseApi soulAppraiseApi;

    @DubboReference
    private UserInfoApi userinfoApi;


    /*获取测灵魂数据*/
    public List<TestSoulVo> getTestSoulInfo() {



        /*倒序查询对应试题的最新报告 以及是否被解锁*/

        List<TestSoulVo> testSoulVoList = new ArrayList<>();

        /*获取当前用户ID*/
        Long userId = UserHolder.getUserId();

        /*获取所有的问卷数据*/
        List<SoulAsk> soulAskList = soulAskApi.getSoulAskList();

        /*根据问卷id获取所有的题*/
        for (SoulAsk soulAsk : soulAskList) {

            TestSoulVo vo = new TestSoulVo();
            TestSoulVo.init(vo,soulAsk);

            Integer askId = soulAsk.getId();  //套题id

            SoulRecord recentRecord = soulRecordApi.getRecentRecord(askId, userId);
            if(recentRecord != null){
                vo.setReportId(recentRecord.getId().toString());   //设置当前报告id
            }


            Integer id = soulAsk.getId();  //问卷id
            /*获取当前题库的所有题目*/
            List<SoulQuestions> allQuestions = soulQuestionApi.getAllQuestionById(id);

            QuestionVo questionVo;
            List<QuestionVo> questionVoList = new ArrayList<>();
            for (SoulQuestions question : allQuestions) {
                questionVo = QuestionVo.init(question);
                /*根据questionId查询对应的option*/
                Integer optionQuestionId = question.getId();
                List<SoulOptions> options = soulQuestionOptionApi.getAllOptionByQuestionId(optionQuestionId);
                List<OptionsVo> optionsVoList = new ArrayList<>();
                for (SoulOptions option : options) {
                    OptionsVo init = OptionsVo.init(option);
                    optionsVoList.add(init);
                }
                questionVo.setOptions(optionsVoList);
                questionVoList.add(questionVo);
            }
            vo.setQuestions(questionVoList);
            vo.setId(soulAsk.getId().toString());   //id 类型不一致
            testSoulVoList.add(vo);
        }


        testSoulVoList.get(0).setIsLock(0);
        for (int i = 1; i < testSoulVoList.size(); i++) {
            String reportId = testSoulVoList.get(i).getReportId();
            if(reportId == null){
                if(testSoulVoList.get(i-1).getReportId() == null){
                    testSoulVoList.get(i).setIsLock(1);
                }else {
                    testSoulVoList.get(i).setIsLock(0);
                }
            }else {
                testSoulVoList.get(i).setIsLock(0);
            }
        }
        return testSoulVoList;

    }



    /*提交答案*/
    public String submitAnswers(List<AnswersDto> list) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();


        Double outgoing = 30d;
        Double judge = 30d;
        Double abstractRate = 30d;
        Double logic = 30d;

        Integer result = 0;
        SoulQuestions questions = soulQuestionApi.getById(list.get(0).getQuestionId());
        Integer questionPageId = questions.getQuestionPageId();

        for (AnswersDto answersDto : list) {
            String optionId = answersDto.getOptionId();
            /*根据optionId查询具体的option,得出分数和其他数据*/
            SoulOptions options =  soulQuestionOptionApi.getById(optionId);
            if(options == null){
                /**/
                throw new BusinessException(ErrorResult.error());
            }
            /*外向抽象理性判断 初始值30%  ab cd ef g  四个区间,每个区间出现一次占7%*/
            Integer score = options.getOptionScore();
            if(score == 1 || score == 2){
                outgoing += 7;
            }else if(score == 3|| score == 4){
                judge += 7;
            }else if(score == 5|| score == 6){
                abstractRate += 7;
            }else if(score == 7) {
                logic += 7;
            }
            result += score;
        }
        SoulRecord soulRecord = new SoulRecord();
        soulRecord.setUserId(userId.intValue());
        soulRecord.setQuestionPageId(questionPageId);
        soulRecord.setRecordScore(result);
        soulRecord.setOutgoing(outgoing);
        soulRecord.setJudge(judge);
        soulRecord.setAbstractRate(abstractRate);
        soulRecord.setLogic(logic);

        String reportedId = soulRecordApi.saveSoulRecord(soulRecord);
        return reportedId;
    }

    /*查询测试结果*/
    public ReportVo report(Long id) {
        //按报告id查询数据库中的灵魂报告结果
        SoulRecord record = soulRecordApi.selectById(id);
        Integer recordScore = record.getRecordScore();
        //按分数和试卷级别查询等级
        SoulAppraise soulAppraise = soulAppraiseApi.getLevel(recordScore);
        //按当前用户所获得的分数和试卷等级查询是否存在推荐用户
        List<SoulRecord> list = soulRecordApi.selectByScore(id,recordScore,record.getQuestionPageId());
        //判断集合是否存在数据
        List<UserInfo> userInfoList = new ArrayList<>();
        if(!list.isEmpty()){
            List<String> ids = new ArrayList<>();
            for (SoulRecord soulRecord : list) {
                String s = soulRecord.getUserId().toString();
                ids.add(s);

            }
            List<Long> userIds = ids.stream().map(a -> Long.parseLong(a)).collect(Collectors.toList());
            userInfoList = userinfoApi.findByIds(userIds);
        }
        ReportVo vo = ReportVo.init(soulAppraise, record, userInfoList);
        return vo;
    }
}
